package indi.lddsdu;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.cn.smart.SmartChineseAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.junit.Test;


/**
 * Created by jack on 18/6/7.
 * 分词的demo
 */
public class ChineseDemo {
    private static String[] strings = {"数据库中存储的数据是结构化数据高富帅，即行数据java，可以用二维表结构来逻辑表达实现的数据。"};
    private static SmartChineseAnalyzer smartChineseAnalyzer = new SmartChineseAnalyzer();
//    private static IKAnalyzer ikAnalyzer = new IKAnalyzer();

    /**
     * 对于传入的字符串进行分词
     * @param str 分词对象字符串
     * @param analyzer 分析器对象
     * @throws IOException
     */
    private static void analyze(String str, Analyzer analyzer) throws IOException {
        StringBuffer sb = new StringBuffer();
        //从分析器对象中获取到tokenStream对象
        TokenStream stream = analyzer.tokenStream("content", str);
        //设置一个引用，相当于是指针，这个引用可以是多种类型，关键词引用，偏移量引用
        CharTermAttribute term = stream.addAttribute(CharTermAttribute.class);
        //设置了偏移量引用
        OffsetAttribute offset = stream.addAttribute(OffsetAttribute.class);
        //这里的reset一定要调用，否则抛出异常
        stream.reset();
        while (stream.incrementToken()){
            String offsetInfo = String.format("start -> %d ; end -> %d", offset.startOffset(), offset.endOffset());
            sb.append("[");
            sb.append(String.format("%-4s",term));
            sb.append("]");
            sb.append(offsetInfo);
            sb.append("\n");
        }
        System.out.println(sb.toString());
    }

    public static void main(String[] args) {
        for (String str : strings){
            try {
               // analyze(str, ikAnalyzer);
            }catch (Exception e){
                System.err.println(e);
            }
        }
    }

    @Test
    public void nulltest(){
        try {
            Integer a = null;
            int b = a;
        }catch (Exception e){
            System.out.println(e);
            System.out.println(e instanceof Exception);
            System.out.println(e instanceof RuntimeException);
        }
    }

}
